﻿using System.Data;
using ExampleApplication.DL;
using ExampleApplication.Models.Base;
using SQLPXBase.Factory;
using SQLPXBase.Factory.Keys;
using SQLPXBase.Factory.Keys.KeyModels;

namespace ExampleApplication.Models
{
    internal class Car : BaseModel
    {
        internal Car(ModelFactory<sql> factory) : base(factory)
        {
        }

        public string PlateNumber { get; set; }
        public string Model { get; set; }


        public LazyKey<Person, sql> OwID { get; protected set; }

        //private LongPK ownerId;
        //public LongPK OwnerId
        //{
        //    get { return ownerId; }
        //    set
        //    {
        //        ownerId = value;
        //        owner = null;
        //    }
        //}



        //// Lazy object Owner
        //private Person owner = null;

        //public Person Owner
        //{
        //    get
        //    {
        //        if (!ownerId.IsEmpty && owner == null)
        //            owner = factory.Load<Person>(ownerId);
        //        return owner;
        //    }
        //}

        #region Overrides of FactorizableModel<sql>

        protected override void Load(PrimaryKey id)
        {
            InitializeFromDB(factory.ProxyManager.GetProxy().Car.Load((LongPK) id));
        }

        protected override void InitializeFromDB(DataRow rw)
        {
            SetPK(new LongPK((long) rw["id"]));

            PlateNumber = rw["plate"] as string ?? "";
            Model = rw["model"] as string ?? "";
            //OwnerId = new LongPK((long) rw["ownerId"]);

            
        }

        #endregion
    }

    internal class CarCollection : ModelCollection<Car>
    {
        #region Loaders

        public class ListByOwner : IModelCollectionLoader<Car, sql>
        {
            private LongPK ownerId;

            public ListByOwner(LongPK ownerId)
            {
                this.ownerId = ownerId;
            }

            public DataTable Load(ModelFactory<sql> factory)
            {
                return factory.ProxyManager.GetProxy().Car.ListByOwner(ownerId);
            }
        }

        #endregion
    }
}
